package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户操作
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        org.springframework.security.core.userdetails.User user =
                (org.springframework.security.core.userdetails.User)
                        SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    @Reference//查找服务
    private UserService userService;

    //新增权限管理项
    @RequestMapping("/add")
    public Result add(@RequestBody User user){
        try{
            userService.add(user);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
            return new Result(false, "添加用户失败");
        }
        return  new Result(true, "添加用户成功");
    }
    //角色管理项分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = userService.pageQuery(queryPageBean);
        return pageResult;
    }

    @RequestMapping("/findAll")
    public Result findAll(){
        try{
            List<User> list = userService.findAll();
            return  new Result(true, "获取角色信息成功",list);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
            return new Result(false, "获取角色信息失败");
        }
    }
}
